from django.shortcuts import render
from django.conf import settings
from rest_framework.views import APIView
from rest_framework.response import Response
from QQLoginTool.QQtool import OAuthQQ
from rest_framework.generics import GenericAPIView, CreateAPIView
from rest_framework import status
import requests
from rest_framework_jwt.settings import api_settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from oauth.models import OAuthQQUser
from oauth.serializers import OAuthQQSerializer
from carts.utils import merge_cart_cookie_to_redis

# Create your views here.

class OAuthQQURLView(APIView):
    """
    提供QQ登陆页面的网址：
    https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=xxx&redirect_uri=xxx&state=xxx
    """

    def get(self, request):
        # 接受前段传递state
        state = request.query_params.get('state')
        if not state:
            state = '/'

        # 构建url
        print(settings.BASE_DIR)
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=state)

        url = oauth.get_qq_url()
        print('QQ登陆网址为：%s'%url)

        # 返回url
        return Response(
            {'login_url': url}
        )


class OAuthQQView(CreateAPIView):
    serializer_class = OAuthQQSerializer

    def get(self, request):
        # 1.获取code
        code = request.query_params.get('code')
        if not code:
            return Response({'message': '缺少code值'}, status=status.HTTP_401_UNAUTHORIZED)
        # 2.通过code获取access_token值
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=next)

        access_token = oauth.get_access_token(code)

        # 3.通过access_token获取openid

        openid = oauth.get_open_id(access_token)

        # 4.判断openid是否绑定
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except:
            # 未绑定过
            # openid加密
            tjs = TJS(settings.SECRET_KEY, 300)
            token = tjs.dumps({'openid': openid}).decode()
            return Response({'access_token': token})

        # 绑定过openid
        user = qq_user.user

        # 生成token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        response = Response(
            {
                'username': user.username,
                'user_id': user.id,
                'token': token
            }
        )
        # 合并购物车
        response = merge_cart_cookie_to_redis(request, response, user)

        return response

    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)
        response = merge_cart_cookie_to_redis(request, response, request.user)

        return response